﻿using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    class AppendBlankPage
    {
        public static void run()
        {
            DateTime dtstart = DateTime.Now;
            AppendBlankPage.AddBlenkPageForOneSide(
                @"C:\Users\licho\AppData\Local\HeYin\AutomationPlatform\Work\flow\拼版完整\4046_单面补白\Temp_190222_110407\t1.pdf",
                @"C:\Users\licho\AppData\Local\HeYin\AutomationPlatform\Work\flow\拼版完整\4046_单面补白\Temp_190222_110407\output\t1.pdf",
                //@"C:\Users\licho\AppData\Local\HeYin\AutomationPlatform\Work\flow\拼版完整\4046_单面补白\Temp_190222_110407\_0020P_LYOC1126360-VER0020P-yh.lu-BJ1902002882-铜板纸250g-单面-彩色-13PX1T.pdf",
                //@"C:\Users\licho\AppData\Local\HeYin\AutomationPlatform\Work\flow\拼版完整\4046_单面补白\Temp_190222_110407\output\_0020P_LYOC1126360-VER0020P-yh.lu-BJ1902002882-铜板纸250g-单面-彩色-13PX1T.pdf",
                4, 2, 2, "数码堆叠", "Landscape");
            DateTime dtEnd = DateTime.Now;
            var len = dtEnd - dtstart;
            Console.WriteLine(len);
            Console.ReadKey();
        }

        public static void AddBlenkPageForOneSide(string strPdfFileSrc, string strPdfFileDst, int upnumber, int wLength, int hLength, string sortMethod, string pageOrientation)
        {
            using (PdfDocument pdfDoc = PdfReader.Open(strPdfFileSrc))
            {
                //获取初始参数
                var n = pdfDoc.PageCount;
                var Upnumber = upnumber;
                var WLength = wLength;
                var HLength = hLength;
                var SortMethod = sortMethod;
                var PageOrientation = pageOrientation;
                

                //计算需要补足的白页
                var addpagesnumber = 0;//作为需要补足的变量
                //var aCropRect = pdfDoc.Pages[0].CropBox;//需要补页的大小按CropBox取值
                var aTrimRect = pdfDoc.Pages[0].TrimBox;
                //var aBleedRect = pdfDoc.Pages[0].BleedBox;
                //var aArtRect = pdfDoc.Pages[0].ArtBox;
                //var aMediaRect = pdfDoc.Pages[0].MediaBox;
                var srcWidth = pdfDoc.Pages[0].Width;
                var srcHeight = pdfDoc.Pages[0].Height;
                if (n < Upnumber)
                {
                    addpagesnumber = Upnumber - n;//假如页数小于拼板数
                }
                else

                {
                    if (n % Upnumber == 0)//假如页数等于拼板数
                    {
                        addpagesnumber = 0;
                    }
                    else
                    { addpagesnumber = Upnumber - (n % Upnumber); }//假如页数大于拼板数

                }
                var pageOne = pdfDoc.Pages[0];

                var aCropRect = pageOne.CropBox;//需要补页的大小按CropBox取值
                pdfDoc.Save(@"C:\Users\licho\AppData\Local\HeYin\AutomationPlatform\Work\flow\拼版完整\4046_单面补白\Temp_190222_110407\output\a-4.pdf");
                //start to insert

                for (var p = 0; p < addpagesnumber; p++)
                {
                    var page = pdfDoc.AddPage();
                    page.Orientation = PdfSharp.PageOrientation.Portrait;
                    page.Width = srcWidth;
                    page.Height = srcHeight;
                    //page.Canvas.
                    //page.CropBox = aCropRect;
                    page.TrimBox = aTrimRect;
                    //page.BleedBox = aBleedRect;
                    //page.ArtBox = aArtRect;
                    //page.MediaBox = aMediaRect;
                }


                //Start to Sort

                //创建堆叠数组

                var ArrayLength = (int)Math.Ceiling((double)n / Upnumber);
                var Index = 0;

                var IndexArray = new int[Upnumber][];
                for (var i = 0; i < Upnumber; i++)
                {          //按Upnumber定义一维长度
                    IndexArray[i] = new int[ArrayLength];    //再声明二维存放Pages
                    for (var j = 0; j < ArrayLength; j++)
                    {      //二维长度为总页数/拼版数
                        IndexArray[i][j] = Index;
                        Index = Index + 1;
                        //app.alert("I="+i+",j="+j+"，Value="+IndexArray[i][j]);
                    }
                }

                //依据堆叠数组生成新的页序

                var NewIndex = new int[ArrayLength * Upnumber];//准备存放新的页序
                var OldIndex = new int[ArrayLength * Upnumber + 1];//老的页序
                Index = 0;
                for (var j = 0; j < ArrayLength; j++)
                {      //按拼板数读取
                    for (var i = 0; i < Upnumber; i++)
                    {          //按二维长度读取
                        NewIndex[Index] = IndexArray[i][j];
                        OldIndex[Index] = Index;
                        //app.alert("Index="+Index+",NewIndex="+NewIndex[Index]);
                        Index = Index + 1;

                    }
                }

                //依据新的顺序，对老文件进行排序

                var x = 0;
                var y = 0;
                var tempvalue = 0;
                n = pdfDoc.PageCount;
                for (var i = 0; i < n; i++)
                {
                    // Move OldIndex Data to last record by newdocArray

                    x = SearchIndex(OldIndex, NewIndex[i]);
                    tempvalue = OldIndex[x];
                    //app.alert("i="+i+",x="+x);
                    //app.alert("n="+n);

                    // sorting OldArray by NewIndex
                    var j = x;
                    for (; j < n; j++)
                    {
                        //app.alert("j="+j);
                        OldIndex[j] = OldIndex[j + 1];
                    }
                    //app.alert("j="+j);
                    OldIndex[j] = tempvalue;


                    //y = n;      //  
                    y = n - 1;      //  
                    //Console.WriteLine("move:" + x + "->" + y);
                    pdfDoc.Pages.MovePage(x, y);
                    //$doc.movePage(x, y);
                }


                //Start to output NewFile


                //Start to output NewFile

                pdfDoc.Save(strPdfFileDst);
            }
        }
        public static void AddBlenkPageForTwoSide(string strPdfFileSrc, string strPdfFileDst, int upnumber, int wLength, int hLength, string sortMethod, string pageOrientation)
        {

            using (PdfDocument pdfDoc = PdfReader.Open(strPdfFileSrc))
            {
                //获取初始参数
                var n = pdfDoc.PageCount;
                var Upnumber = upnumber;
                var WLength = wLength;
                var HLength = hLength;
                var SortMethod = sortMethod;
                var PageOrientation = pageOrientation;


                var FinalPages = (int)(2 * (Math.Ceiling((double)n / 2) + (Math.Ceiling((double)n / 2) % Upnumber)));

                //Sorting pages by odd&even,1,2,3,4,5,6,7...=>1,3,5...;2,4,6...奇偶排序
                //奇偶页拆分
                //var nOdd = (int)Math.Ceiling((double)n / 2);
                //var nEven = n - nOdd;
                var nEven = n / 2;
                var nOdd = n - nEven;

                int x, y, i;
                for (i = 0; i < nEven; i++)
                {
                    // movePage x, toAfterPage y
                    // note page numbers are 0-indexed
                    x = i + 1; //
                    y = n - 1; //  
                    //y = n;
                    pdfDoc.Pages.MovePage(x, y);
                }

                //inserting blank pages into end of odd，在奇数页后补足空白
                var nOddnAddPages = 0;
                var aCropRect = pdfDoc.Pages[0].CropBox;//需要补页的大小按CropBox取值
                var aTrimRect = pdfDoc.Pages[0].TrimBox;
                var aBleedRect = pdfDoc.Pages[0].BleedBox;
                var aArtRect = pdfDoc.Pages[0].ArtBox;
                var aMediaRect = pdfDoc.Pages[0].MediaBox;
                if ((nOdd % Upnumber) != 0) //如果正好是拼版数的倍数，则不补
                {
                    nOddnAddPages = Upnumber - (nOdd % Upnumber);
                    //app.alert("nOddnAddPages："+nOddnAddPages);
                    for (var p = 0; p < nOddnAddPages; p++)
                    {
                        //var nstartpage = nOdd - 1;
                        var nstartpage = nOdd;
                        var page = pdfDoc.InsertPage(nstartpage);
                        page.CropBox = aCropRect;
                        page.TrimBox = aTrimRect;
                        page.BleedBox = aBleedRect;
                        page.ArtBox = aArtRect;
                        page.MediaBox = aMediaRect;

                        //$doc.setPageBoxes("Crop", nOdd, nOdd, aCropRect);
                        //$doc.setPageBoxes("Trim", nOdd, nOdd, aTrimRect);
                        //$doc.setPageBoxes("Bleed", nOdd, nOdd, aBleedRect);
                        //$doc.setPageBoxes("Art", nOdd, nOdd, aArtRect);
                        //$doc.setPageBoxes("Media", nOdd, nOdd, aMediaRect);
                    }
                }
                //inserting blank pages into end of even 在偶数页后面补足空白
                var nEvennAddPages = 0;
                var isEven = false;
                if (Math.Abs(nOdd - nEven) == 1) //如果文档是奇数页，则需要额外多补一个白页
                {
                    nEven = nEven + 1;
                    isEven = true; //设置是奇数页标志
                }
                if ((nEven % Upnumber) != 0) //如果正好是拼版数的倍数，则不补
                {
                    nEvennAddPages = Upnumber - (nEven % Upnumber);
                    if (isEven == true)
                    {
                        nEvennAddPages = nEvennAddPages + 1;
                    }
                    //app.alert("nEvennAddPages："+nEvennAddPages);
                    for (var p = 0; p < nEvennAddPages; p++)
                    {
                        //var nstartpage = pdfDoc.PageCount - 1;
                        var nstartpage = pdfDoc.PageCount;
                        //app.alert("nstartpage="+nstartpage);

                        var page = pdfDoc.InsertPage(nstartpage);
                        page.CropBox = aCropRect;
                        page.TrimBox = aTrimRect;
                        page.BleedBox = aBleedRect;
                        page.ArtBox = aArtRect;
                        page.MediaBox = aMediaRect;

                    }
                }
                //pdfDoc.Save(strPdfFileDst);
                //app.alert("补足空白OK!");
                //创建堆叠数组
                var ArrayLength = (int)Math.Ceiling((double)pdfDoc.PageCount / Upnumber / 2); //逻辑关系，先拆分单偶2列，然后分别再除以拼板数拆成堆叠,也就是拼版后的页数
                var FrontArray = new int[ArrayLength][][]; //先声明1维数组存放 拼板后的页数
                var BackArray = new int[ArrayLength][][]; //先声明1维数组存放 拼板后的页数
                var Index = 0;
                if (SortMethod == "数码堆叠") //按数码堆叠方式排序
                {

                    //生产正面堆叠数组
                    var s = ArrayLength;
                    for (i = 0; i < ArrayLength; i++)
                    {
                        var t = 0; //做拼版数循环
                        FrontArray[i] = new int[WLength][]; //按WLength定义2维长度，即列数
                        for (x = 0; x < WLength; x++)
                        {
                            FrontArray[i][x] = new int[HLength]; //再按Hlength声明3维存放行数
                            for (y = 0; y < HLength; y++)
                            {
                                Index = 2 * (i + t * s);
                                FrontArray[i][x][y] = Index;
                                t = t + 1;
                                //app.alert("I="+i+",x="+x+",y="+y+"，Value="+FrontArray[i][x][y]);
                            }
                        }
                    }

                    //app.alert("生产正面堆叠数组OK!");
                    //生产反面堆叠数组
                    Index = 0;

                    s = ArrayLength;
                    for (i = 0; i < ArrayLength; i++)
                    {
                        var t = 0;
                        BackArray[i] = new int[WLength][]; //按WLength定义2维长度，即列数
                        for (x = 0; x < WLength; x++)
                        {
                            BackArray[i][x] = new int[HLength]; //再按Hlength声明3维存放行数
                            for (y = 0; y < HLength; y++)
                            {
                                Index = 2 * (i + t * s) + 1;
                                BackArray[i][x][y] = Index;
                                t = t + 1;
                                //app.alert("I="+i+",x="+x+",y="+y+"，Value="+BackArray[i][x][y]);
                            }
                        }
                    }
                }
                //app.alert("生产反面堆叠数组OK");
                //依据堆叠数组生成新的页序
                Index = 0;
                var NewIndex = new int[ArrayLength * (WLength * HLength * 2)]; //准备存放新的页序
                for (i = 0; i < ArrayLength; i++) //根据 拼板后的页序读
                {
                    //读取正面页序
                    for (x = 0; x < WLength; x++)
                    {
                        for (y = 0; y < HLength; y++)
                        {
                            NewIndex[Index] = FrontArray[i][x][y];

                            //app.alert("Index="+Index+",NewIndex[Index]="+NewIndex[Index]);
                            Index = Index + 1;
                        }
                    }

                    //读取反面页序

                    for (x = 0; x < WLength; x++)
                    {
                        for (y = 0; y < HLength; y++)
                        {

                            var t = 0;
                            if (WLength >= HLength || PageOrientation == "Portrait")
                            {
                                t = HLength - y - 1; //横向拼版
                            }
                            else //纵向拼版
                            {
                                t = y;
                            }

                            //app.alert("WLength="+WLength+",HLength="+HLength+",i="+i+",x="+x+",y="+y+",s="+s+",t="+t+",Value="+BackArray[i][x][t]);
                            NewIndex[Index] = BackArray[i][x][t];
                            //app.alert("WLength="+WLength+",HLength="+HLength);
                            //app.alert("Index="+Index+",NewIndex[Index]="+NewIndex[Index]);
                            Index = Index + 1;
                        }
                    }
                }

                var CurrentNumPages = pdfDoc.PageCount;
                var OldIndex = new int[CurrentNumPages + 1]; //老的页序
                Index = 0;

                //先装奇数
                for (i = 0; i < CurrentNumPages / 2; i++)
                {
                    OldIndex[Index] = 2 * i;

                    //app.alert("Index="+Index+"，OldIndex="+OldIndex[Index]);
                    Index = Index + 1;

                }
                //再装偶数
                for (i = 0; i < CurrentNumPages / 2; i++)
                {
                    OldIndex[Index] = 2 * i + 1;

                    //app.alert("Index="+Index+"，OldIndex="+OldIndex[Index]);
                    Index = Index + 1;


                }

                //依据新的顺序，对老文件进行排序
                x = 0;
                y = 0;
                var tempvalue = 0;
                CurrentNumPages = pdfDoc.PageCount;
                //app.alert("CurrentNumPages="+CurrentNumPages);
                for (i = 0; i < CurrentNumPages; i++)
                {
                    // Move OldIndex Data to last record by newdocArray
                    x = SearchIndex(OldIndex, NewIndex[i]);
                    tempvalue = OldIndex[x];
                    //app.alert("i="+i+",x="+x);
                    //app.alert("CurrentNumPages="+CurrentNumPages);
                    // sorting OldArray by NewIndex
                    var j = 0;
                    for (j = x; j < CurrentNumPages; j++)
                    {
                        //app.alert("j="+j);
                        OldIndex[j] = OldIndex[j + 1];
                    }
                    //app.alert("j="+j);
                    OldIndex[j] = tempvalue;

                    y = CurrentNumPages - 1; //  
                    //y = CurrentNumPages;

                    pdfDoc.Pages.MovePage(x, y);
                }

                pdfDoc.Save(strPdfFileDst);
            }
        }
        static int SearchIndex(int[] arr, int value)
        {
            for (var i = 0; i < arr.Length; i++)
            {
                if (arr[i] == value)
                    return i;
            }
            return -1;
        }

    }
}
